<?php

namespace Admin\Service;

/**
 * 角色管理页面 model(数据层)
 *
 * @package         YDCMS
 * @author          QQ:644157559 <644157559@qq.com>
 * @version         $Id: SysAdminUserModel.class.php v1.0 2014-06-13 17:27:03 $
 */
class AdminService extends CommonService {
    
    /**
     * 保存添加管理员信息
     * @param array $userinfo
     * @return type
     */
    public function addSysUser($userinfo) {
        $SysUser = $this->getD();
        //$this->startTrans();
        if (false === ($User = $SysUser->create($userinfo))) {
            return $this->errorResultReturn($SysUser->getError());
        }
        //处理密码
        $password = password($User['pwd']);
        $User['pwd'] = $password['password'];
        $User['salt'] = $password['salt'];
        $as = $SysUser->add($User);

        $roleAdmin = array(
            'role_id' => $User['role_id'],
            'user_id' => $SysUser->getLastInsId()
        );
        $ras = M('RoleAdmin')->add($roleAdmin);

        if (false === $as) {
            //$this->rollback();
            return $this->errorResultReturn('系统出错了！');
        }

        //$this->commit();
        return $this->resultReturn(true);
    }
    
    /**
     * 更新管理员信息
     * @param type $userinfo
     * @return type
     */
    public function updateSysUser($userinfo) {
        $SysUser = $this->getD();
        if (false === ($User = $SysUser->create($userinfo))) {
            return $this->errorResultReturn($SysUser->getError());
        }
        if (empty($User['pwd'])) {
            unset($User['pwd']);
        }else{
            //处理密码
            $password = password($User['pwd']);
            $User['pwd'] = $password['password'];
            $User['salt'] = $password['salt'];
        }
        if (false === $SysUser->save($User)) {
            return $this->errorResultReturn($this->getError());
        }
        
        M('RoleAdmin')->where("user_id={$User['id']}")
                      ->save(array('role_id' => $User['role_id']));
        return $this->resultReturn(true);
    }
    
    /**
     * 删除管理员
     * @param type $id
     * @return type
     */
    public function deleteSysUser($id) {
        if(intval($id) <= 1){
            return $this->errorResultReturn("超级管理员不能删除！");
        }
        $map = array();
        $map['id'] = array("gt", 1);
        $map['id'] = array("eq", intval($id));
        if(!$this->getD()->where($map)->delete()){
            return $this->errorResultReturn("系统错误！");
        }
        M("RoleAdmin")->where(array("user_id" => $id))->delete();
        return $this->resultReturn(true);
    }
    
    
    
    /**
     * 获取管理员列表
     * @return type
     */
    public function getSysUserList(){
        return $this->getM()->field("a.*, r.name")->alias("a")->join("__ROLES__ r ON a.role_id = r.id")->select();
    }

    /**
     * 获取管理员信息
     * @param int $id
     */
    public function getSysUserInfo($id, $relation = false) {
        return $this->getD()->relation($relation)->getById($id);
    }
    /**
     * 获取管理员信息
     * @param string $username
     * @return array
     */
    public function getByUserName($username) {
        return $this->getM()->where(array('username' => $username))->find();
    }
    
    /**
     * 获取角色下的管理员
     * @param type $id
     */
    public function getByRoleId($role_id) {
        return $this->getM()->where(array('role_id' => $role_id))->select();
    }
    /**
     * 生成登录shell
     * @param  int    $id       shell的id
     * @param  string $password shell的密码
     * @return string
     */
    private function genShell($id, $password) {
        return md5($password . C('AUTH_TOKEN')) . $id;
    }
    
    public function genByIdShell($id) {
        $account = $this->getM()->getById($id);
        return $this->genShell($id, $account['pwd']);
    }
    /**
     * 获取加密后的密码
     * @param type $pwd
     * @param type $salt
     * @return type
     */
    private function genPwd($pwd, $salt){
        $password = password($pwd, $salt);
        return $password['password'];
    }

    /**
     * 账户是否启用
     * @param  string  $email email
     * @return boolean
     */
    public function isStatus($username) {
        $where = array(
            'username' => $username,
            'status' => 1
        );

        if ($this->getM()->where($where)->count() > 0) {
            return true;
        }

        return false;
    }
    /**
     * 设置状态
     * @param  int   $id     id
     * @param  int   $status 状态
     * @return mixed
     */
    public function setStatus($id, $status) {
        return $this->getM()->where("id={$id}")->save(array('status' => $status));
    }
    /**
     * 管理员登录认证
     * @param  array $admin 管理员信息
     * @return array
     */
    public function login($admin) {
        $SysUser = $this->getM();
        // 用户名是否存在
        if (!$this->existAccount($admin['username'])) {
            return $this->errorResultReturn('用户名不存在！');
        }

        $account = $this->getByUserName($admin['username']);
        
        // 密码验证
        if ($account['pwd'] != $this->genPwd($admin['pwd'], $account['salt'])) {
            return $this->errorResultReturn('密码不正确！');
        }

        // 是否启用
        if (!$this->isStatus($admin['username'])) {
            return $this->errorResultReturn('账户已被禁用！');
        }

        $loginMarked = C('LOGIN_MARKED');
        $shell = $this->genShell($account['id'], $account['pwd']);

        // 生成登录session
        setSession($loginMarked, $shell);

        // 生成登录cookie
        $shell .= '_' . time();
        setcookie($loginMarked, $shell, 0, '/');
        unset($account['pwd'], $account['salt']);
        //设置Session
        setSession('current_account', $account);
        setSession('sid', getSessionId());

        // 权限认证
        if (C('USER_AUTH_ON')) {
            setSession(C('USER_AUTH_KEY'), $account['id']);
            if ($account['is_super']) {
                // 超级管理员无需认证
                setSession(C('ADMIN_AUTH_KEY'), true);
            }

            // 缓存访问权限
            \Org\Util\Rbac::saveAccessList();
        }

        // 更新最后登录时间
        $SysUser->where("id={$account['id']}")
              ->save(array('logintime' => time(), 'loginip' => get_client_ip()));

        return $this->resultReturn(true);
    }
    /**
     * 检查登录状态
     * @return array
     */
    public function checkLogin() {
        $loginMarked = C('LOGIN_MARKED');
        // 是否已登录
        if (!isset($_COOKIE[$loginMarked])) {
            return $this->errorResultReturn('login');
        }

        // 是否登录超时
        $cookie = explode('_', $_COOKIE[$loginMarked]);
        $timeout = C('LOGIN_TIMEOUT');
        if (time() > (end($cookie) + $timeout)) {
            $this->unsetLoginMarked();

            return $this->errorResultReturn('登录超时，请重新登录！');
        }

        // 是否帐号异常
        if ($cookie[0] != $_SESSION[$loginMarked]) {
            $this->unsetLoginMarked();

            return $this->errorResultReturn('账户异常，请重新登录！');
        }

        // 重新设置过期时间
        setcookie($loginMarked, $cookie[0] . '_' . time(), 0, '/');
        return $this->resultReturn(true);
    }
    
    /**
     * 管理员登出
     * @return
     */
    public function logout() {
        $this->unsetLoginMarked();

        if (C('USER_AUTH_ON')) {
            unset($_SESSION[C('USER_AUTH_KEY')]);
            unset($_SESSION[C('ADMIN_AUTH_KEY')]);
        }

        session_destroy();
    }
    /**
     * 销毁登录标记
     * @return
     */
    private function unsetLoginMarked() {
        $loginMarked = C('LOGIN_MARKED');
        setcookie("{$loginMarked}", null, -3600, '/');
        unset($_SESSION[$loginMarked], $_COOKIE[$loginMarked]);

        return ;
    }
    
    /**
     * 是否存在帐号
     * @param  string  $email email
     * @return boolean
     */
    public function existAccount($username) {
        if ($this->getM()->where("username='{$username}'")->count() > 0) {
            return true;
        }
        return false;
    }

    protected function getModelName() {
        return "Admin";
    }

}
